package com.xopencode.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import javax.sound.midi.Soundbank;

/**
 * 服务器端的业务处理类
 * @Author mcb
 * @Version 1.0
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    //数据的读取事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("serverHandler--ctx:"+ctx);
        ByteBuf buffer= (ByteBuf) msg;
        System.out.println("来自客户端的消息："+buffer.toString(CharsetUtil.UTF_8));
    }

    //数据读取完毕事件
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ChannelFuture channelFuture = ctx.writeAndFlush(Unpooled.copiedBuffer("hi,client,我收到你的消息啦！", CharsetUtil.UTF_8));
        //添加监听事件：数据发送完毕之后，直接断开客户端的连接
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }

    //异常捕捉事件
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
